﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Mindfor.Web.Data;
using Mindfor.Web.Routing;
using NHibernate;
using NHibernate.Linq;

namespace Mindfor.Web.Mvc.Controllers
{
	/// <summary>
	/// Defines methods to manipulate with sys options.
	/// </summary>
	[CmsAuthorize(CmsRoles.Administrator)]
	public class SysOptionController : CmsController
	{
		/// <summary>
		/// Returns view with options list.
		/// </summary>
		[AdminLink("Системные настройки", "Система управления")]
		public ActionResult Index()
		{
			ViewData.Model = Data.Query<ModuleOption>();
			return View();
		}

		/// <summary>
		/// Returns edit view for sys option.
		/// </summary>
		[HttpGet]
		[LoadModelState]
		[UrlRoute("{id}/Edit")]
		[UrlRouteConstraint("id", Constraints.IsInt)]
		public ActionResult Edit(int id)
		{
			// get option
			ModuleOption model = Data.Get<ModuleOption>(id);
			if (model == null)
				return HttpNotFound();

			// return view
			ViewData.Model = model;
			if (ViewBag.Value == null)
				ViewBag.Value = model.GetValue().ToString();
			ViewBag.CancelUrl = Url.Action("Index");
			return View();
		}

		/// <summary>
		/// Commits edit for sys option.
		/// </summary>
		[HttpPost]
		[UrlRouteSkip]
		[ValidateInput(false)]
		public ActionResult Edit(int id, string value)
		{
			// get option
			ModuleOption o = Data.Get<ModuleOption>(id);
			if (o == null)
				return HttpNotFound();

			// set value
			bool ok = o.SetValue(value);
			if (!ok)
				ModelState.AddModelError("value", "Введите корректное значение для данного типа");

			if (ModelState.IsValid)
			{
				// commit and redirect
				using (ITransaction t = Data.BeginTransaction())
				{
					Data.Update(o);
					t.Commit();
				}
				return RedirectToAction("Index");
			}
			else
			{
				this.SaveModelState();
				return RedirectToAction("Edit", new { id });
			}
		}
	}
}
